<!--
 * @Description: 内容列表
 * @Version: 1.0
 * @Autor: chen_yt
 * @Date: 2020-09-14 14:50:30
 * @LastEditors: wei_jt@ecidi.com
 * @LastEditTime: 2022-07-13 14:31:20
-->

<template>
  <div style="height: 100%">
    <fks-query-page
      v-loading="tableLoading"
      :data="tableData"
      :total="total"
      :page-size.sync="pageSize"
      :current-page.sync="pageNo"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 50, 100]"
      :element-loading-text="LANG.LOADING"
      :table-name="_tableTitle"
      @query="getList"
      @clear="clear"
      @selection-change="handleSelectionChange"
      @sort-change="sortHandle"
    >
      <template slot="search">
        <fks-search-item :label="LANG.TITLE">
          <fks-input
            id="title"
            v-model="searchFrom.title"
            style="min-width: 100px"
            :placeholder="LANG.INPUT_TITLE"
            @keyup.enter.native="search"
          />
        </fks-search-item>
        <fks-search-item :label="LANG.STATUS">
          <fks-select
            v-model="searchFrom.status"
            style="min-width: 100px"
            :placeholder="LANG.CHOOSE_STATUS"
            clearable
          >
            <fks-option
              v-for="status in contentStatus"
              :key="status.code"
              :value="status.code"
              :label="status[$lang]"
            />
          </fks-select>
        </fks-search-item>
      </template>

      <template slot="button">
        <div>
          <fks-button
            v-show="_categoryId != ''"
            v-permission="['content:add']"
            type="primary"
            icon="fks-icon-plus"
            @click="addContent"
          >
            {{ LANG.ADD }}
          </fks-button>
          <!-- <fks-button
          type="primary"
          @click="delMultiContent"
          icon="fks-icon-delete"
        >
          {{ LANG.MULTI_DEL }}
        </fks-button>-->
        </div>
      </template>

      <template>
        <!-- <fks-table-column
          type="selection"
          width="55"
          header-align="center"
          align="center"
        ></fks-table-column>-->
        <fks-table-column
          label="#"
          width="55"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </fks-table-column>
        <!-- 固定第一位显示title -->
        <template v-for="item in templateDetail">
          <template v-if="item.isReveal == '1'">
            <template v-if="item.fieldName == 'TITLE'">
              <fks-table-column
                :key="item.fieldName"
                sortable="custom"
                align="left"
                is-link
                :label="LANG.TITLE"
                :min-width="minWidth(item.fieldName)"
                :max-width="maxWidth(item.fieldName)"
                @link="rowClick"
              >
                <template slot-scope="scope">
                  <span>
                    {{
                      scope.row[item.fieldName + 'ForShow']
                        ? scope.row[item.fieldName + 'ForShow'].fieldValue
                        : ''
                    }}
                  </span>
                </template>
              </fks-table-column>
              <!-- 固定第二位显示所属分类目录 -->
              <fks-table-column
                v-if="_categoryId == '' || !_categoryId"
                :key="item.fieldName + randomKey"
                align="left"
                width="300px"
                :label="LANG.CATEGORY_NAME"
              >
                <template slot-scope="scope">
                  <span>
                    {{ getCategoryById(scope.row.content.categoryId).name }}
                  </span>
                </template>
              </fks-table-column>
            </template>
          </template>
        </template>
        <template v-for="item in templateDetail">
          <template v-if="item.isReveal == '1'">
            <fks-table-column
              v-if="item.fieldName != 'TITLE'"
              :key="item.fieldName"
              :sortable="
                item.fieldName == 'CREATEDATE' || item.fieldName == 'UPDATEDATE'
                  ? 'custom'
                  : false
              "
              :align="alignDecide(item.fieldName)"
              :label="item.alias"
              :prop="decideProp(item.fieldName)"
              header-align="center"
              :min-width="minWidth(item.fieldName)"
              :max-width="maxWidth(item.fieldName)"
            >
              <template slot-scope="scope">
                <span>
                  {{
                    scope.row[item.fieldName + 'ForShow']
                      ? scope.row[item.fieldName + 'ForShow'].fieldValue
                      : ''
                  }}
                </span>
              </template>
            </fks-table-column>
          </template>
        </template>

        <!-- 根据状态变色 -->
        <fks-table-column
          :label="LANG.STATUS"
          header-align="center"
          width="150"
          prop="stauts"
        >
          <template slot-scope="scope">
            <span>
              <fks-tag :type="scope.row.statusTag">
                {{ getStatusDescription(scope.row.status) }}
              </fks-tag>
            </span>
          </template>
        </fks-table-column>

        <!-- 操作区，根据内容状态及用户权限渲染不同按钮 -->
        <fks-table-column
          :label="LANG.OPERATION"
          header-align="center"
          align="left"
          width="150"
        >
          <span slot-scope="scope">
            <fks-button
              v-if="scope.row.status != 'PUBLISH' && scope.row.status != 'TOP'"
              v-permission="['content:audit']"
              type="text"
              @click="topManage(scope.row, 'publish')"
              >{{ LANG.PUBLISH }}</fks-button
            >
            <fks-button
              v-if="scope.row.status === 'AUDIT'"
              v-permission="['content:audit']"
              type="text"
              :loading="scope.row.fallLoading"
              @click="failure(scope.row)"
              >{{ LANG.FALL_BACK }}</fks-button
            >

            <fks-button
              v-if="
                scope.row.status != 'PUBLISH' &&
                scope.row.status != 'TOP' &&
                scope.row.status != 'AUDIT'
              "
              v-permission="['content:edit']"
              type="text"
              @click="gotoEdit(scope.row)"
              >{{ LANG.EDIT }}</fks-button
            >

            <fks-button
              v-if="scope.row.status == 'PUBLISH' || scope.row.status == 'TOP'"
              v-permission="['content:audit']"
              type="text"
              @click="topManage(scope.row, 'top')"
              >{{ LANG.TOP }}</fks-button
            >
            <fks-button
              v-if="scope.row.status == 'PUBLISH' || scope.row.status == 'TOP'"
              v-permission="['content:audit']"
              class="revoke"
              type="text"
              :loading="scope.row.revokeLoading"
              @click="revoke(scope.row)"
              >{{ LANG.REVOKE }}</fks-button
            >
            <fks-button
              v-permission="['content:delete']"
              type="text"
              style="color: #ff4d4f"
              @click="deleteContent(scope.row.id)"
              >{{ LANG.DELETE }}</fks-button
            >

            <!-- 更多按钮，可查看历史版本-->
            <!-- <fks-dropdown
              v-permission="['content:dropdown']"
              @command="dropdownClick($event, scope.row.id)"
            >
              <span class="fks-dropdown-link">
                <fks-button
                  type="text"
                  style="margin-left: 15px"
                  icon="fks-icon-more"
                >
                </fks-button>
              </span>
              <fks-dropdown-menu slot="dropdown">
                <fks-dropdown-item command="revision">
                  {{ LANG.VIEW_REVISION }}
                </fks-dropdown-item>
                <fks-dropdown-item v-if="scope.row.canEdit" command="edit">
                    {{ LANG.EDIT }}
                  </fks-dropdown-item>
              </fks-dropdown-menu>
            </fks-dropdown>-->
          </span>
        </fks-table-column>
      </template>
    </fks-query-page>
    <div class="dialogs">
      <top-manage
        ref="TopManage"
        :operate-type="status_operateType"
        :visible="visible_top_manage"
        :content-id="current_contentId"
        :content-title="current_title"
        :user-set-date="publishDate_user"
        :status-code="statusCode"
        @close="closeTopManage"
        @submit="submitTopManage"
      />
      <content-history
        ref="ContentHistory"
        :visible="visible_content_history"
        :content-id="current_contentId"
        @close="visible_content_history = false"
      />
    </div>
    <router-view />
    <dialog-read
      :id="read_dialog_id"
      :title="read_dialog_title"
      :visible="read_dialog_visible"
      @close="closeReadDialog"
    />
  </div>
</template>

<script>
import { deleteContentById } from './api/index'
import {
  getCategoryList,
  getContentList,
  getTemplateDetailById,
  getStatusDescription,
  getTagTypeByStatus,
  getCategoryById,
  addContentStatus,
  updateES,
  getLastPublish,
  updateContentStatus
} from '@/modules/Content/api'
import {
  defaultField,
  detialInContent,
  defaultMinLength,
  defaultMaxLength,
  defaultAlign
} from '@/modules/Content/defaultData'
import TopManage from './components/Dialogs/TopManage/index'
import ContentHistory from './components/Dialogs/ContentHistory/index'
import { USER, ENUM } from '@/store/State/stateTypes'
import DialogRead from './components/DialogRead/index'
import mix from '@/mixins/module'
export default {
  name: 'ContentList',
  components: {
    TopManage,
    ContentHistory,
    DialogRead
  },
  mixins: [mix],
  props: {
    categoryId: {
      type: String,
      default: ''
    },
    tableTitle: {
      type: String
    }
  },
  data() {
    return {
      read_dialog_visible: false,
      read_dialog_id: '',
      read_dialog_title: '',
      tableLoading: true,
      visible_content_history: false,
      visible_top_manage: false,
      revokeLoading: false,
      fallLoading: false,
      pageNo: 1,
      id: null,
      pageSize: 20,
      total: 0,
      columnName: '',
      sort: '',
      statusCode: '',
      current_contentId: '',
      current_title: '',
      publishDate_user: '',
      categoryName: '',
      status_operateType: 'publish',
      operate_type: 'new',
      loadFlag: 0,
      tableData: [],
      select_row: [],
      content_list: [],
      category_List: [],
      templateDetail: [],
      searchFrom: {}
    }
  },
  computed: {
    USER() {
      return this.$store.state[USER]
    },
    contentStatus() {
      return this.$store.state[ENUM].contentStatus || []
    },
    allCategorys() {
      return this.category_List
    },
    _categoryId() {
      if (this.categoryId) {
        return this.categoryId
      }
      return ''
    },
    _tableTitle() {
      if (this.tableTitle) {
        return this.tableTitle
      }
      if (this.categoryName) {
        return this.categoryName
      }
      return this.LANG.ALL_CONTENT
    },
    randomKey() {
      return Math.random() * 1000
    }
  },
  watch: {
    _categoryId(val) {
      this.tableLoading = true
      this.tableData = []
      this.templateDetail = []
      this.content_list = []
      this.getTemplateDetail()
    }
  },
  mounted() {
    // this.initCategory()
    this.getTemplateDetail()
  },
  created() {
    this.initCategory()
  },
  beforeDestroy() {},
  methods: {
    /**
     * @description: 排序响应
     * @param {prop,order} sort
     */
    sortHandle(sort) {
      this.columnName = sort.prop
      if (!sort.order) {
        this.sort = ''
        this.columnName = ''
      } else {
        this.sort = sort.order === 'ascending' ? 'asc' : 'desc'
      }
      this.getList()
    },

    /**
     * @description: 更多的下拉
     * @param {*} command
     * @param {*} id
     */
    dropdownClick(command, id) {
      if (command == 'revision') {
        this.current_contentId = id
        this.visible_content_history = true
      }
    },

    gotoEdit(row) {
      this.$router.push({
        name: 'edit',
        query: {
          ContentId: row.id
        }
      })
    },

    decideProp(prop) {
      if (prop == 'CREATEDATE') return 'createDate'
      if (prop == 'UPDATEDATE') return 'updateDate'
      return prop
    },

    alignDecide(name) {
      if (defaultAlign[name] == 1) return 'left'
      return 'center'
    },

    minWidth(name) {
      return defaultMinLength[name] ? defaultMinLength[name] : 300
    },
    maxWidth(name) {
      return defaultMaxLength[name] ? defaultMaxLength[name] : ''
    },

    /**
     * @description: 批量操作预留
     * @param {Array}  rows 所有已选中行
     */
    handleSelectionChange(rows) {
      this.select_row = rows
    },

    /**
     * @description: 批量删除
     */
    delMultiContent() {
      if (this.select_row.length == 0) {
        this.$message({
          showClose: true,
          message: this.LANG.ERROR_NOROW,
          type: 'error'
        })
        return
      }
      let contentIdList = []
      this.select_row.forEach((item) => {
        contentIdList.push(item.id)
      })
      this.deleteContent(contentIdList.join())
    },

    /**
     * @description: 新增/编辑内容时，向弹出的Dialog置入属性
     *
     */
    addContent() {
      this.visible_EditDialog = true
      this.$router.push({
        name: 'edit',
        query: {
          CategoryId: this._categoryId
        }
      })
    },

    /**
     * @description: 审核退回
     */
    failure(row) {
      if (row.status != 'AUDIT') {
        this.$message({
          type: 'error',
          message: this.LANG.ERROR_NOT_AUDIT
        })

        return
      }
      let contentId = row.id
      let failure = [
        {
          status: 'FAILURE',
          contentId: contentId
        }
      ]
      row.fallLoading = true
      addContentStatus(failure)
        .then((res) => {
          if (res.status) {
            setTimeout(() => {
              this.initData()
              row.fallLoading = false
            }, 1000)
          } else {
            row.fallLoading = false
          }
        })
        .catch(() => {
          row.failLoading = false
        })
    },

    /**
     * @description: 撤下
     */
    revoke(row) {
      let contentId = row.id
      let now = this.$dayjs().locale('zh-cn').format('YYYY-MM-DD HH:mm:ss')
      row.revokeLoading = true
      getLastPublish(contentId)
        .then((res) => {
          if (res.status) {
            let count = 0
            let length = res.data.length
            for (let i = 0; i < length; i++) {
              let item = res.data[i]
              if (item.status == 'PUBLISH') {
                let temp = item
                temp.endTime = now
                updateContentStatus(temp)
                  .then((res) => {
                    if (res.status) {
                      count++
                      if (count == length) {
                        setTimeout(() => {
                          this.initData()
                          row.revokeLoading = false
                        }, 1000)
                      }
                    } else {
                      row.revokeLoading = false
                    }
                  })
                  .catch(() => {})
              }
              /**
               * @description: 被撤下的内容有置顶状态，直接删除置顶状态信息
               */
              if (item.status == 'TOP') {
                let temp = item
                temp.deleteFlag = -1
                updateContentStatus(temp)
                  .then((res) => {
                    if (res.status) {
                      count++
                      if (count == length) {
                        setTimeout(() => {
                          this.initData()
                          row.revokeLoading = false
                        }, 1000)
                      }
                    } else {
                      row.revokeLoading = false
                    }
                  })
                  .catch(() => {})
              }
            }
          } else {
            row.revokeLoading = false
          }
        })
        .catch(() => {})
    },

    /**
     * @description: 对发布、置顶状态的管理
     * @param {Object}  row 选中行
     */
    topManage(row, type) {
      if (row.status == 'DRAFT' || row.status == 'FAILURE') {
        this.$confirm(this.LANG.GOTO_EDIT, this.LANG.TIPS, {
          cancelButtonClass: 'fks-icon-close',
          confirmButtonClass: 'fks-icon-check',
          type: 'warning'
        })
          .then(() => {
            this.$router.push({
              name: 'edit',
              query: {
                ContentId: row.id
              }
            })
          })
          .catch(() => {})
        return
      }

      this.current_contentId = row.id
      this.current_title = row['TITLE'].fieldValue
      this.publishDate_user = ''
      if (
        row['AUTOPUBLISHFLAG'] != null &&
        row['AUTOPUBLISHFLAG'].fieldValue == '1' &&
        row['PUBLISHDATE'] != null
      ) {
        this.publishDate_user = row['PUBLISHDATE'].fieldValue
      }

      this.statusCode = row.status
      this.status_operateType = type
      this.openTopManage()
    },

    /**
     * @description: 流程表单设计,未实现
     */
    processContent(row) {
      let formType = 'ContentStatus'
      this.$router.history.push({
        path: this.$route.path + `/form/add/${formType}`
      })
    },

    /**
     * @description: 删除内容
     * @param {String}  id 内容id拼接出的String
     */
    deleteContent(contentIdList) {
      this.$confirm(this.LANG.DELETE_CONFIRM, this.LANG.TIPS, {
        confirmButtonText: this.LANG.DELETE,
        cancelButtonText: this.LANG.CANCEL,
        confirmButtonClass: 'fks-button--danger',
        deleteMode: true,
        type: 'warning'
      })
        .then(() => {
          deleteContentById(contentIdList)
            .then((res) => {
              // updateES()
              if (res.status) {
                this.$message({
                  type: 'success',
                  message: this.LANG.DELETE_SUCCESS
                })
                this.resetData()
              }
            })
            .catch(() => {})
        })
        .catch(() => {})
    },

    /**
     * @description: 弹窗控制
     *
     */
    openTopManage() {
      this.visible_top_manage = true
    },
    closeTopManage() {
      this.visible_top_manage = false
      this.current_contentId = ''
      this.current_title = ''
      this.publishDate_user = ''
      this.status_operateType = 'publish'
    },
    submitTopManage() {
      this.closeTopManage()
      this.getList()
    },

    closeReadDialog() {
      this.read_dialog_visible = false
    },

    /**
     * @description: 跳转详情页
     * @param {Object}  row
     *                  row.id为内容id
     */
    rowClick({ row }) {
      // this.$router.push({
      //   path: './Read/' + row.id
      // })
      this.read_dialog_id = row.id
      this.read_dialog_title = row.content.title
      this.read_dialog_visible = true
    },

    /**
     * @description: 获得内容列表
     *
     */
    @permission('content:list:query')
    getList: async function () {
      this.tableLoading = true
      this.tableData = []
      this.loadFlag = 0
      await this.getContentList()
      this.tableLoading = false
    },
    getContentList() {
      let temp = {
        page: this.pageNo,
        size: this.pageSize,
        categoryId: this._categoryId,
        createFullname: this.searchFrom.createFullname,
        status: this.searchFrom.status,
        title: this.searchFrom.title,
        startDate: this.searchFrom.startDate,
        endDate: this.searchFrom.endDate,
        columnName: this.columnName,
        sort: this.sort
      }
      return getContentList(temp)
        .then((res) => {
          if (res.status) {
            this.content_list = []
            if (res.data == null) {
              this.total = 0
              return
            }
            /**
             * @description: 由于响应较慢，此处控制回调是否为本系列信息
             */
            if (res.data.categoryId != this._categoryId) {
              return
            }

            for (let i = 0; i < res.data.contentList.length; i++) {
              let item = res.data.contentList[i]

              item.id = res.data.contentList[i].content.id
              this.getDetailListById(item)
              this.getStatus(item)
              this.content_list.push(item)
            }
            this.setTableData()
            this.total = res.data.itemNumber
          }
        })
        .catch(() => {
          this.content_list = []
        })
    },

    /**
     * @description: 根据获得的content列表与获得contentDetail数据，置入table展示
     */
    setTableData: function () {
      this.tableData = []
      for (let i = 0; i < this.content_list.length; i++) {
        let temp = JSON.parse(JSON.stringify(this.content_list[i]))
        temp.revokeLoading = false
        temp.fallLoading = false
        this.tableData.push(temp)
      }
    },

    /**
     * @description: 根据内容id获得它的详情列表
     */
    getDetailListById: async function (item) {
      let data = item.detailList
      data.forEach((field) => {
        item[field.fieldName] = field
        if (
          field.fieldType == 'orgSelector' ||
          field.fieldType == 'userSelector'
        ) {
          item[field.fieldName].fieldValue = JSON.parse(
            item[field.fieldName].fieldValue
          )
        }
        if (detialInContent.indexOf(field.fieldType) > -1) {
          item[field.fieldName].fieldValue = item.content[field.fieldType]
        }
        /**
         * @description: [xxx'ForSHow']用于展示
         */
        item[field.fieldName + 'ForShow'] = JSON.parse(
          JSON.stringify(item[field.fieldName])
        )
        if (field.fieldType == 'radio') {
          item[field.fieldName + 'ForShow'].fieldValue =
            item[field.fieldName].fieldValue == 0 ? this.LANG.NO : this.LANG.YES
        }
        if (field.fieldType == 'userSelector') {
          item[field.fieldName + 'ForShow'].fieldValue =
            item[field.fieldName].fieldValue.createFullname
        }
        if (field.fieldType == 'orgSelector') {
          item[field.fieldName + 'ForShow'].fieldValue =
            item[field.fieldName].fieldValue.createDept
        }
      })
    },

    /**
     * @description: 获取内容的Status
     */
    getStatus(item) {
      let data = ''

      for (let i = 0; i < item.statusHistoryList.length; i++) {
        if (item.statusHistoryList[i].status == 'TOP') {
          data = 'TOP'
          break
        } else {
          data = item.statusHistoryList[i].status
        }
      }

      item.status = data
      // item.statusForShow = this.getStatusDescription(data)
      item.statusTag = getTagTypeByStatus(data)
      item.canEdit =
        item.status == 'DRAFT' ||
        item.status == 'FAILURE' ||
        item.status == 'REVOKE'
          ? true
          : false
    },

    /**
     * @description: 根据id获得分类目录
     * @param {String}  Id
     * @return {Object} category
     */
    getCategoryById(id) {
      for (let i = 0; i < this.allCategorys.length; i++) {
        if (this.allCategorys[i].id == id) return this.allCategorys[i]
      }
      let obj = { name: '' }
      return obj
    },

    /**
     * @description: 根据当前语言，获取status.code对应的status.name
     * @param {String}  status.code
     * @return {String} status.name
     */
    getStatusDescription(statusCode) {
      return getStatusDescription(statusCode, this.contentStatus, this.$lang)
    },

    /**
     * @description: 获得该分类目录采用的模板细节
     */
    getTemplateDetail: async function () {
      let templateId
      //当没有传入分类目录id时，使用默认模板
      if (this._categoryId == '' || !this._categoryId) {
        this.categoryName = this.LANG.ALL_CONTENT
        this.templateDetail = defaultField
        this.resetData()
      } else {
        //当传入分类目录id时，获取该目录的模板
        await getCategoryById(this._categoryId)
          .then((res) => {
            if (res.status) {
              if (res.data.length > 0) {
                templateId = res.data[0].templateId
                this.categoryName = res.data[0].categoryName
              }
            }
          })
          .catch((err) => {})

        if (templateId) {
          getTemplateDetailById(templateId)
            .then((res) => {
              if (res.status) {
                this.templateDetail = res.data
                this.resetData()
              }
            })
            .catch(() => {})
        } else {
          this.templateDetail = defaultField
          this.resetData()
        }
      }
    },

    /**
     * @description: 初始获得所有分类目录，
     *               完成后获取所有内容
     */
    initCategory() {
      this.category_List = []
      let temp = {
        page: 1,
        size: 5000
      }
      getCategoryList(temp)
        .then((res) => {
          if (res.status) {
            let data = res.data.voList
            data.forEach((item) => {
              let obj = {
                id: item.category.id,
                name: item.category.categoryName,
                templateId: item.category.templateId
              }

              this.category_List.push(obj)
            })
          }
        })
        .catch(() => {})
    },

    /**
     * @description: 保留搜索条件，回到第一页
     */
    search() {
      this.pageNo = 1
      this.getList()
    },

    /**
     * @description: 清清空搜索条件并回到第一页
     */
    clear() {
      this.pageNo = 1
      this.searchFrom = {}
      this.initData()
    },
    resetData() {
      this.clear()
    },
    initData() {
      this.getList()
    },
    pageSizeChange(size) {
      this.pageSize = size
      this.initData()
    },
    pageChange(page) {
      this.pageNo = page
      this.initData()
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .revoke.fks-button.is-loading::before {
  background: transparent !important;
}
</style>
